<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="请假员工ID，外键关联员工表" prop="EmployeeID">
        <el-input
          v-model="queryParams.EmployeeID"
          placeholder="请输入请假员工ID，外键关联员工表"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请假开始日期" prop="StartDate">
        <el-date-picker clearable
          v-model="queryParams.StartDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择请假开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="请假结束日期" prop="EndDate">
        <el-date-picker clearable
          v-model="queryParams.EndDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择请假结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:leaves:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:leaves:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:leaves:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:leaves:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leavesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="请假记录的唯一标识" align="center" prop="leaveid" />
      <el-table-column label="请假员工ID" align="center" prop="employeeid" />
      <el-table-column label="部门id" align="center" prop="departmentid" />
      <el-table-column label="请假类型" align="center" prop="leavetype" />
      <el-table-column label="请假状态" align="center" prop="leavestatus" />
      <el-table-column label="请假开始时间" align="center" prop="startdate" />
      <el-table-column label="请假结束时间" align="center" prop="enddate" />
      
      <el-table-column label="请假原因" align="center" prop="reason" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:leaves:edit']">允许</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:leaves:remove']">不允许</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination      
  :total="total"
  v-model:currentPage="queryParams.pageNum"
  v-model:pageSize="queryParams.pageSize"
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"
  layout="total, sizes, prev, pager, next, jumper"
/>

    <!-- 添加或修改存储员工请假信息对话框 -->
    <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="leavesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="请假员工ID，外键关联员工表" prop="EmployeeID">
          <el-input v-model="form.EmployeeID" placeholder="请输入请假员工ID，外键关联员工表" />
        </el-form-item>
        <el-form-item label="请假开始日期" prop="StartDate">
          <el-date-picker clearable
            v-model="form.StartDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择请假开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假结束日期" prop="EndDate">
          <el-date-picker clearable
            v-model="form.EndDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择请假结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假原因" prop="Reason">
          <el-input v-model="form.Reason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="Leaves">
import { getCurrentInstance,ref,reactive,toRefs} from 'vue';
import { listLeaves, getLeaves, delLeaves, addLeaves, updateLeaves } from "@/api/system/leaves";

const { proxy } = getCurrentInstance();
import { ElMessage ,ElMessageBox} from 'element-plus';

const leavesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    employeeid: null,
    LeaveType: null,
    StartDate: null,
    EndDate: null,
    Reason: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询存储员工请假信息列表 */
function getList() {
  loading.value = true;
  listLeaves(queryParams.value).then(response => {
    console.log("response",response)
    leavesList.value = response.list;
    total.value = response.total;
    loading.value = false;
  });
}
// 分页
function handleSizeChange(newSize) {
  queryParams.pageSize = newSize;
  queryParams.pageNum = 1; // 重置页码为第一页
  getList();
}

function handleCurrentChange(newPage) {
  queryParams.pageNum = newPage;
  getList();
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
const leavesRef = ref(null);
// 表单重置
function reset() {
  form.value = {
    LeaveID: null,
    EmployeeID: null,
    LeaveType: null,
    StartDate: null,
    EndDate: null,
    Reason: null
  };
  
  if (leavesRef.value) { // 确保 usersRef 不是 null
    leavesRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.LeaveID);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储员工请假信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  try {
    // 假设 row 是一个查询参数，如用户ID或记录ID
    // 使用 encodeURIComponent 来确保 URL 编码正确
    const leaveid=row.leaveid
   
    console.log(row.leaveid)
    console.log( leaveid)
    
    const response = await fetch(`http://localhost:8080/api/leaves/update/${leaveid}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
   
    if (!response.ok) {
      throw new Error('网络响应不正常');
    }
    ElMessage({
            message: '新增成功',
            type: 'success'
          }); 
    // 如果后端返回 JSON 数据，可以解析它
    const data = await response.json();
    console.log('考勤记录更新成功：', data);
  } catch (error) {
    console.error('更新考勤记录失败：', error);
  }
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["leavesRef"].validate(valid => {
    if (valid) {
      if (form.value.LeaveID != null) {
        updateLeaves(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLeaves(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 删除按钮操作 */
const handleDelete = async (row) => {
  try {
    // 假设 row 是一个查询参数，如用户ID或记录ID
    // 使用 encodeURIComponent 来确保 URL 编码正确
    const leaveid=row.leaveid
   
    console.log(row.leaveid)
    console.log( leaveid)
    
    const response = await fetch(`http://localhost:8080/api/leaves/updatetono/${leaveid}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
   
    if (!response.ok) {
      throw new Error('网络响应不正常');
    }
    ElMessage({
            message: '不允许成功',
            type: 'success'
          }); 
    // 如果后端返回 JSON 数据，可以解析它
    const data = await response.json();
    console.log('考勤记录更新成功：', data);
  } catch (error) {
    console.error('更新考勤记录失败：', error);
  }
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/leaves/export', {
    ...queryParams.value
  }, `leaves_${new Date().getTime()}.xlsx`)
}

getList();
</script>
